<template>
  <Drawer v-model="Dmodal"
      transfer
      title="优惠券"
      :mask-closable="true"
      width="900">
      <div class="search-box">
        <Row type="flex">
          <Row type="flex"
            justify="start"
            class="search-item-left">
            <Col class="search-item">
              <span class="search-label">优惠券名称:</span>
              <Input placeholder="请输入"
                v-model="couponName"
                @on-keyup="filterSpace"></Input>
            </Col>
            <Col class="search-item">
              <span class="search-label">类型:</span>
              <Select v-model="searchObj.couponType" @on-change="drawSearch">
                <Option :value="-1">全部</Option>
                <Option v-for="item in couponTypeList" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </Col>
            <Col class="search-item">
              <Button class="search-btn"
                type="primary"
                @click="drawSearch">查询</Button>
            </Col>
            <Col class="search-item">
              <Button class="search-btn"
                @click="drawReset">重置</Button>
            </Col>
          </Row>
        </Row>
      </div>
      <Table
        class="table-list"
        :max-height="550"
        highlight-row
        stripe
        @on-current-change="handleCouponCurrent"
        :columns="drawerColumns"
        :data="drawerData"
      ></Table>
      <Row type="flex">
        <Col span="24">
          <div class="page-box">
            <Page :total="total"
              :page-size="pageSize"
              :current="pageIndex"
              show-total
              show-sizer
              @on-change="changePageIndex"
              @on-page-size-change="changePageSize" />
          </div>
        </Col>
      </Row>
      <Row type="flex"
        justify="end"
        class="bottom-form-item"
        style="width: 100%; padding: 20px 30px; border-top: 1px solid #e8eaec; position: absolute; right: 0; bottom: 0;">
        <Col>
          <Button style="width: 80px"
            @click="Dmodal = false">取消</Button>
          <Button type='primary'
            style="margin-left: 20px; width: 80px"
            @click="ensureTie">确定</Button>
        </Col>
      </Row>
    </Drawer>
</template>
<script>
import { mapState } from 'vuex'
import enumsMixin from '@/view/market/enums.js'
import { getCouponLists } from '@/api/market/coupon.js'
let that
export default {
  name: 'DrawerCouponSingle',
  mixins: [enumsMixin],
  data () {
    return {
      Dmodal: false,
      couponName: '',
      searchObj: {
        couponName: '',
        couponType: -1
      },
      drawerColumns: [
        {
          title: '选择',
          key: 'action',
          align: 'center',
          render: (h, params) => {
            let cla = ['ivu-radio']
            if (params.row.couponBase.couponId === this.selectedData.refId) {
              cla = ['ivu-radio', 'ivu-radio-checked']
            }
            return h(
              'span',
              {
                class: cla
              },
              [
                h('span', {
                  class: ['ivu-radio-inner']
                })
              ]
            )
          }
        },
        {
          title: '优惠券名称',
          key: 'couponName',
          width: 150,
          render: (h, params) => {
            return h('span', params.row.couponBase && params.row.couponBase.couponName)
          }
        },
        {
          title: '面额',
          key: 'couponName',
          render: (h, params) => {
            return h('span', (params.row.couponBase.couponType === 1 ? Number(params.row.extraData.promotionAmount) * 1000 / 100 : params.row.extraData.promotionAmount) + (params.row.couponBase.couponType === 0 ? '元' : params.row.couponBase.couponType === 1 ? '折' : '枚'))
          }
        },
        {
          title: '类型',
          key: 'couponType',
          render: (h, params) => {
            return h('span', params.row.couponBase && this.getEnumsName(params.row.couponBase.couponType, this.couponTypeList))
          }
        },
        {
          title: '有效期',
          key: 'validTime',
          render: (h, params) => {
            return h(
              'span',
              params.row.couponBase && params.row.couponBase.expirationType ? (params.row.couponBase.startTime + '至' + params.row.couponBase.endTime) : (params.row.couponBase.dayNum + '天')
            )
          }
        },
        {
          title: '使用渠道',
          key: 'channel',
          render: (h, params) => {
            return h(
              'span',
              this.getChannelsName(params.row.rules && params.row.rules[0].matchRules.channel)
            )
          }
        },
        {
          title: '最低使用金额(元)',
          key: 'accumAmount',
          width: 150,
          render: (h, params) => {
            return h(
              'span',
              params.row.rules && params.row.rules[0].processRules[0].accumAmount
            )
          }
        }
      ],
      drawTableHeight: 200,
      drawerData: [],
      total: 0,
      pageIndex: 1,
      pageSize: 10,
      selectedData: {}
    }
  },
  props: {
    value: {
      type: Boolean
    },
    data: {
      type: Object
    },
    // 获取类型 默认活动赠送
    origin: {
      type: Number,
      default: -1
    }
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId
    })
  },
  beforeCreate: function () {
    that = this
  },
  watch: {
    value (val) {
      if (val) {
        this.drawReset()
        this.selectedData = JSON.parse(JSON.stringify(this.data))
      }
      this.Dmodal = val
    },
    Dmodal (val) {
      this.$emit('input', val)
    }
  },
  mounted () {
    this.calcDrawTableHeight()
    window.addEventListener('resize', this.calcDrawTableHeight)
  },
  methods: {
    getChannelsName (value) {
      if (value) {
        return value.map((value) => {
          const result = that.channelList.filter(item => +item['value'] === +value)
          return result[0] ? result[0]['label'] : ''
        }).join(',')
      }
      return ''
    },
    filterSpace () {
      this.couponName = this.couponName.replace(/\s+/g, '')
    },
    search () {
      this.pageIndex = 1
      this.getData()
    },
    drawSearch () {
      this.searchObj.couponName = this.couponName
      this.search()
    },
    drawReset () {
      this.pageIndex = 1
      this.pageSize = 10
      this.couponName = ''
      this.searchObj = {
        couponName: '',
        couponType: -1
      }
      this.getData()
    },
    getData () {
      let params = {
        merchantId: this.merchantId,
        couponName: this.searchObj.couponName,
        status: 1,
        offset: (this.pageIndex - 1) * this.pageSize,
        limit: this.pageSize
      }
      if (this.origin !== -1) {
        params.originType = this.origin
      }
      if (this.searchObj.couponType !== -1) {
        params.couponType = this.searchObj.couponType
      }
      getCouponLists(params).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.drawerData = result.data || []
          this.total = result.totalCount || 0
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    ensureTie () {
      this.$emit('sure', this.selectedData)
    },
    handleCouponCurrent (val) {
      this.selectedData = {
        refId: val.couponBase.couponId,
        refName: val.couponBase.couponName,
        refType: val.couponBase.couponType,
        expirationType: val.couponBase.expirationType,
        startTime: val.couponBase.startTime,
        endTime: val.couponBase.endTime,
        dayNum: val.couponBase.dayNum,
        channel: val.rules[0].matchRules.channel,
        accumAmount: val.rules[0].processRules[0].accumAmount
      }
    },
    changePageIndex (page) {
      this.pageIndex = page
      this.getData()
    },
    changePageSize (size) {
      this.pageSize = size
      this.search()
    },
    calcDrawTableHeight () {
      const clientHeight = document.documentElement.clientHeight || document.body.clientHeight
      this.drawTableHeight = clientHeight - 300
    }
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.calcDrawTableHeight)
  }
}
</script>
<style>
  #drawerTable.ivu-table-wrapper {
    overflow: hidden !important;
  }
</style>
